package cn.leizp.springboot.auth.frontweb.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import cn.leizp.springboot.auth.frontweb.entity.User;
import cn.leizp.springboot.auth.frontweb.repository.UserRepository;

@Controller
public class HtmlController {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @GetMapping("/")
    public String index(Model model) {
        model.addAttribute("message", "Welcome to the home page!");
        return "home";
    }

    @GetMapping("/admin")
    public String adminPage(Model model) {
        model.addAttribute("message", "Welcome to the admin page!");
        return "admin";
    }

    @GetMapping("/login")
    public String login(Model model) {
        return "login";
    }

    @GetMapping("/register-login")
    public String register(Model model) {
        return "register";
    }

    @PostMapping("/register-login")
    public String registerUser(@RequestParam String username, @RequestParam String password) {
        String encodedPassword = passwordEncoder.encode(password);
        User user = new User(username, encodedPassword);
        userRepository.save(user);
        return "redirect:/login";
    }
}
